package com.cloudeasy.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeasy.server.constant.UserRoleConstant;
import com.cloudeasy.server.mapper.UserRoleMapper;
import com.cloudeasy.server.po.Permission;
import com.cloudeasy.server.po.UserRole;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleService extends ServiceImpl<UserRoleMapper, UserRole> {
    private final RoleService roleService;

    public UserRoleService(RoleService roleService) {
        this.roleService = roleService;
    }


    /**
     * 获取用户角色可用记录
     *
     * @param userId 用户Id
     * @return {@link List<UserRole>}
     */
    public List<UserRole> getEnableListByUserId(String userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("status", UserRoleConstant.NORMAL);
        return this.list(queryWrapper);
    }

    /**
     * 判断是否有管理员角色
     *
     * @param userId 用户Id
     * @return {@link Boolean}
     */
    public Boolean hasAdminRole(String userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("user_id",userId)
                .ne("level", -1);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 获取可用权限
     *
     * @param userId 用户Id
     * @return {@link List<Permission>}
     */
    public List<Permission> getEnablePermission(String userId) {
        List<String> roleIds = this.getEnableListByUserId(userId).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if (roleIds.size() == 0) {
            return null;
        }
        return roleService.getEnablePermission(roleIds);
    }
}
